package com.own.business.system.menu.business.hook;

import com.own.business.system.menu.business.service.SystemMenuService;
import com.own.business.system.menu.business.service.SystemRolePermissionService;
import com.own.business.system.menu.business.service.SystemRoleService;
import com.own.business.system.menu.business.service.SystemUserRoleService;
import com.own.business.system.menu.entity.po.SystemRole;
import com.own.component.common.hook.BaseRoleHook;
import com.own.component.common.login.user.BaseLoginUser;
import com.own.component.common.util.list.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * SystemUserRoleHook
 *
 * @author chenxueli
 * @date 2024-04-08 16:38:00
 */
@Slf4j
@Component
public class SystemUserRoleHook implements BaseRoleHook {

    @Resource
    private SystemRoleService systemRoleService;
    @Resource
    private SystemUserRoleService systemUserRoleService;
    @Resource
    private SystemMenuService systemMenuService;
    @Resource
    private SystemRolePermissionService systemRolePermissionService;

    /**
     * 获取角色名称列表
     *
     * @param loginUser 登录的用户信息
     * @return 角色名称列表
     */
    @Override
    public Collection<String> getRoleNameList(BaseLoginUser loginUser) {
        // 根据用户id获取对应的角色列表
        var roleList = systemRoleService.listByUserId(loginUser.userId(), loginUser.client());
        return roleList.stream().map(SystemRole::getName).collect(Collectors.toSet());
    }

    /**
     * 获取某一个菜单的操作信息
     *
     * @param loginUser 登录的用户信息
     * @param module    模块信息
     * @return 操作权限列表
     */
    @Override
    public Collection<String> getModuleOperation(BaseLoginUser loginUser, String module) {
        // 获取用户id对应的角色id列表
        var roleIdList = systemUserRoleService.listRoleIdListByUserId(loginUser.userId());
        // 获取模块菜单的key
        var menu = systemMenuService.getByModule(module, loginUser.client());
        // 根据用户id和模块名称获取对应的权限列表
        var permissionList = systemRolePermissionService.listPermissionByRoleIdListAndMenuId(roleIdList, menu.getId());
        // 解析数据
        return permissionList.stream().flatMap(permission -> ListUtil.Spilt.to(permission, ",").stream()).collect(Collectors.toSet());
    }

}
